/*************************************************************************
 *  Copyright © 2023-2030 FXB CO.,LTD. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：UPMProject
 *  文件：PackageInstallManager.cs
 *  作者：Administrator
 *  日期：2024/12/27 14:57:8
 *  功能：Nothing
*************************************************************************/

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using SVNPackageManager.Runtime;
using UnityEditor;
using System.Threading.Tasks;
using System;

namespace SVNPackageManager.Editor
{
    [System.Serializable]
    public class PackageInstallManager
    {
        public ScopedRegistryConfig svnScopedRegistryConfig;
        public SVNHelper svnHelper;

        public PackageInstallManager(SVNHelper svnHelper, PackageResourceManage resourceManage)
        {
            svnScopedRegistryConfig = resourceManage.svnScopedRegistryConfig;
            this.svnHelper = svnHelper;
        }

        public async Task<PacakgeStateMessage> InstallPackage(PackageItemInfo packageInfo, SVNProgressEventHandler progressHandler)
        {
            Debug.Log($"下载包{packageInfo.packageConfig.name}:{packageInfo.packageConfig.version} from {packageInfo.packageSvnUrl}");

            string localPackagePath = InstallPackagePath($"{packageInfo.packageConfig.name}_v{packageInfo.packageConfig.version}");

            //这里在下载的时候需要考虑到这个包之前下载过，如果已经下载过并且存在直接安装
            await svnHelper.CheckoutFolderAsync(packageInfo.packageSvnUrl, localPackagePath, progressHandler);

            PacakgeStateMessage state = await PackageInstaller.InstallPackageFromDisk(localPackagePath);
            state.packageItemID = packageInfo.packageItemID;
            if (state.isSuccess)
                state.data = localPackagePath;

            return state;
        }

        public async Task<PacakgeStateMessage> RemovePackage(PackageItemInfo packageInfo)
        {
            Debug.Log($"卸载包{packageInfo.packageConfig.name}:{packageInfo.packageConfig.version}");

            PacakgeStateMessage state = await PackageInstaller.RemovePackage(packageInfo.packageConfig.name);
            state.packageItemID = packageInfo.packageItemID;

            return state;
        }

        private string InstallPackagePath(string packageName)
        {
            if (string.IsNullOrEmpty(svnScopedRegistryConfig.checkOutPath))
                return Path.Combine(PackagePathManage.LocalPackageParentPath, packageName);
            return Path.Combine(svnScopedRegistryConfig.checkOutPath, packageName);
        }

        public void ImportSampleResources(PackageItemInfo packageInfo, int sampleIndex)
        {
            PackageConfig packageConfig = packageInfo.packageConfig;
            string sourcePath = Path.Combine(packageInfo.resolvedPath, packageConfig.samples[sampleIndex].path);
            string destinationPath = Path.Combine(Application.dataPath
                , packageConfig.displayName
                , packageConfig.displayName + packageConfig.version
                , packageConfig.samples[sampleIndex].displayName);

            if (Directory.Exists(sourcePath))
            {
                CopyDirectory(sourcePath, destinationPath);
                AssetDatabase.Refresh();
                Debug.Log("Sample resources have been imported to :" + sourcePath);
            }
            else
            {
                Debug.LogWarning("Sample resources path does not exist: " + sourcePath);
            }
        }

        private void CopyDirectory(string sourceDir, string destinationDir)
        {
            // 创建目标目录如果不存在
            if (!Directory.Exists(destinationDir))
            {
                Directory.CreateDirectory(destinationDir);
            }

            // 复制所有文件
            foreach (var file in Directory.GetFiles(sourceDir))
            {
                string targetFilePath = Path.Combine(destinationDir, Path.GetFileName(file));
                File.Copy(file, targetFilePath, true);
            }

            // 递归复制所有子目录
            foreach (var directory in Directory.GetDirectories(sourceDir))
            {
                string targetDirectoryPath = Path.Combine(destinationDir, Path.GetFileName(directory));
                CopyDirectory(directory, targetDirectoryPath);
            }
        }
    }
}


